package com.workhours.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.workhours.dto.StatisticsRequest;
import com.workhours.service.StatisticsService;
import com.workhours.vo.Result;
import com.workhours.vo.StatisticsVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 统计控制器
 * 
 * @author WorkHours
 * @since 2025-09-19
 */
@Slf4j
@Tag(name = "统计管理", description = "工作和休息时间统计")
@RestController
@RequestMapping("/api/statistics")
@RequiredArgsConstructor
public class StatisticsController {

    private final StatisticsService statisticsService;

    /**
     * 获取用户工作和休息统计
     * 
     * @param request 统计请求参数
     * @return 统计结果
     */
    @Operation(summary = "获取统计数据", description = "计算用户在指定时间范围内的工作和休息统计")
    @PostMapping
    public Result<StatisticsVO> getStatistics(@Valid @RequestBody StatisticsRequest request) {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("收到统计请求: userId={}, request={}", userId, request);
        
        try {
            StatisticsVO statistics = statisticsService.calculateStatistics(userId, request);
            log.info("统计计算成功: {}", statistics);
            return Result.success("计算成功", statistics);
        } catch (IllegalArgumentException e) {
            log.warn("统计计算参数错误: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("统计计算失败", e);
            return Result.error("计算失败，请重试");
        }
    }

    /**
     * 获取默认统计（从出差开始到今天）
     * 
     * @return 统计结果
     */
    @Operation(summary = "获取默认统计", description = "获取从出差开始日期到今天的统计数据")
    @GetMapping("/default")
    public Result<StatisticsVO> getDefaultStatistics(
            @RequestParam(value = "includeTravel", defaultValue = "false") Boolean includeTravel) {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("收到默认统计请求: userId={}, includeTravel={}", userId, includeTravel);
        
        try {
            StatisticsRequest request = new StatisticsRequest();
            request.setIncludeTravel(includeTravel);
            
            StatisticsVO statistics = statisticsService.calculateStatistics(userId, request);
            log.info("默认统计计算成功: {}", statistics);
            return Result.success("计算成功", statistics);
        } catch (IllegalArgumentException e) {
            log.warn("默认统计计算参数错误: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("默认统计计算失败", e);
            return Result.error("计算失败，请重试");
        }
    }
}
